//
//  HeartBeatPacketCenter.m
//  HiQServer
//
//  Created by shoguncao on 12-8-8.
//  Copyright (c) 2012年 __MyCompanyName__. All rights reserved.
//

#import "HeartBeatPacketCenter.h"
#import "MacroComd.h"
#import "MainSocketDelegate.h"
#import "MiniSocket.h"

@implementation HeartBeatPacketCenter

// 收到心跳包
- (void)MessageDispatch: (SockPacket *)packet
{
    UTF8Char * bytes = (UTF8Char *)[packet.packetContent bytes] + sizeof(NSInteger)*2;
    NSInteger userId = *((NSUInteger *) bytes);
    
    if (userId == 10001)
    {
        int aa = 99;
        aa = 100;
    };
    
    @synchronized([MainSocketDelegate theHeartBeatQueue])
    {
        BOOL isFind = NO;
        
        for (NSInteger i=0; i<[[MainSocketDelegate theHeartBeatQueue] count]; ++i)
        {
            HeartBeat *heartBeat = [[MainSocketDelegate theHeartBeatQueue] objectAtIndex:i];
            if (heartBeat.userId == userId)
            {
                isFind = YES;
                heartBeat.beatTime = [NSDate date];
            }
        }
        if (isFind == NO)
        {
            HeartBeat *newHeartBeat = [[HeartBeat alloc] init];
            newHeartBeat.beatTime = [NSDate date];
            newHeartBeat.subAsynSocket = packet.subAsynSocket;
            newHeartBeat.userId = userId;
            [[MainSocketDelegate theHeartBeatQueue] addObject:newHeartBeat];
        }
        
        [self sendHeartBeatPacket:packet.subAsynSocket];
    }  
}

// 发送心跳包
- (void)sendHeartBeatPacket:(GCDAsyncSocket *)socket
{
    NSInteger sendLen = sizeof(NSInteger) * 2;
    NSInteger type = CMD_FUN_HEART_BEAT;
    NSInteger operation = 0;
    
    NSMutableData *sendData = [[NSMutableData alloc] initWithBytes:&sendLen length:sizeof(sendLen)];
    [sendData appendBytes:&type length:sizeof(type)];
    [sendData appendBytes:&operation length:sizeof(operation)];
    
    [socket writeData:sendData withTimeout:-1 tag:0];
}

@end
